package fyp.spedmew;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.api.client.util.DateTime;

import java.io.File;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import fyp.spedmew.backend.entity.jobEndpoint.model.Address;
import fyp.spedmew.backend.entity.jobEndpoint.model.Job;
import fyp.spedmew.backend.entity.userEndpoint.model.User;
import fyp.spedmew.connector.JobInsertATask;
import fyp.spedmew.connector.UploadImageATask;
import fyp.spedmew.connector.UserFindByPhoneATask;
import fyp.spedmew.util.Login;
import fyp.spedmew.util.Utility;
import fyp.spedmew.util.Validator;

public class CreateJobDetailActionBarActivity extends ActionBarActivity {

    private static final String TAG = new Object(){}.getClass().getCanonicalName();

    private Bundle jobData = new Bundle();
    private String title, desc, shipDate, price, pic;
    private String pickupLoc, deliveryLoc, recipientNo, customInstruction,id;
    private String recipientName;
    private Uri image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_job_summary);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Intent in = getIntent();
        jobData = in.getExtras();

        title = jobData.getString("name");
        desc = jobData.getString("descr");
        shipDate = jobData.getString("date");
        price = jobData.getString("price");
        pic = jobData.getString("pic");
        pickupLoc = jobData.getString("pickupLoc");
        deliveryLoc = jobData.getString("dropoffLoc");
        recipientNo = jobData.getString("recipientNo");
        customInstruction = jobData.getString("customIns");
        image = Uri.parse( jobData.getString("pic"));
        id = jobData.getString("id");
        ImageView imageView = (ImageView) findViewById(R.id.SimgView);
        imageView.setImageURI(image);

        try {
            recipientName = new UserFindByPhoneATask().execute(recipientNo).get().getName();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        ((TextView)findViewById(R.id.nameTxt)).setText(title);
        ((TextView)findViewById(R.id.descTxt)).setText(desc);
        ((TextView)findViewById(R.id.dateTxt)).setText(shipDate);
        ((TextView)findViewById(R.id.priceTxt)).setText(price);
        ((TextView)findViewById(R.id.pickupTxt)).setText(pickupLoc);
        ((TextView)findViewById(R.id.dropoffTxt)).setText(deliveryLoc);
        ((TextView)findViewById(R.id.recipNameTxt)).setText(recipientName);
        ((TextView)findViewById(R.id.recipientTxt)).setText(recipientNo);
        ((TextView)findViewById(R.id.customTxt)).setText(customInstruction);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_create__shipment5, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private Long saveToDB(Job job)
    {
        try {
            return new JobInsertATask().execute(job).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void sendMessage(View view) {
        final Button btn = (Button) findViewById(R.id.submit_btn);
        btn.setBackgroundColor(getResources().getColor(R.color.button_BG_OnPressed));

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                btn.setBackgroundColor(getResources().getColor(R.color.button_BG));
            }
        }, 300);

        // Define toast setting
        Context context = getApplicationContext();
        CharSequence text;
        int duration = Toast.LENGTH_LONG;
        Toast toast;

        Intent out = new Intent(this, UserListActionBarActivity.class);
        Address pickupAddr = new Address();
        pickupAddr.setLine1(pickupLoc);

        Address deliveryAddr = new Address();
        deliveryAddr.setLine1(deliveryLoc);

        User sender = null;
        User recipient = null;
        try {
            sender = Login.getUser();
            recipient = new UserFindByPhoneATask().execute(recipientNo).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        Job toSave = new Job();
        toSave.setTitle(title);
        toSave.setDetail(desc);
        toSave.setShipDate(Utility.convertStringToDateTime(shipDate));
        toSave.setPickupAddress(pickupAddr);
        toSave.setDeliverAddress(deliveryAddr);
        toSave.setSenderId(sender.getId());
        toSave.setRecipientId(recipient.getId());
        toSave.setInstruction(customInstruction);
        toSave.setPrice(price);
        toSave.setCreatedDate(new DateTime(new Date()));

        Long jobId;
        Log.i(TAG, "Save entity done");

        switch(Validator.checkJob(toSave)) {

            case 'P':
                jobId = saveToDB(toSave);
                uploadImage(jobId, image);
                startActivity(out);
                break;

            case 'A':
                text = "Price entered should be a positive value";
                toast = Toast.makeText(context, text, duration);
                toast.show();
                break;

            case 'B':
                text = "Item name cannot be blank";
                toast = Toast.makeText(context, text, duration);
                toast.show();
                break;

            case 'C':
                text = "Item description cannot be blank";
                toast = Toast.makeText(context, text, duration);
                toast.show();
                break;

            case 'D':
                text = "Drop-off location cannot be blank";
                toast = Toast.makeText(context, text, duration);
                toast.show();
                break;

            case 'E':
                text = "Pick-up location cannot be blank";
                toast = Toast.makeText(context, text, duration);
                toast.show();
                break;
        }
    }

    public void uploadImage(Long jobId, Uri imageUri) {
        String filePath = getRealPathFromURI(getApplicationContext(), imageUri);
        File imageFile = new File(filePath);
        new UploadImageATask().execute(imageFile, jobId);
    }

    public String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
}
 